import 'package:flutter/material.dart';
import 'package:flutter_base/provider_demo4/pages/second.dart';
import 'package:provider/provider.dart';
import 'package:flutter_base/provider_demo4/models/task.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: globalTaskList,
      builder: (context, child) => const MaterialApp(
        home: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int idIndex = 129;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('首页')),
      body: Center(
          child: Column(
        children: <Widget>[
          Consumer<TaskList>(
            builder: (context, taskList, child) => SizedBox(
              height: 300.0,
              child: ListView.builder(
                itemBuilder: (context, index) => taskList.tasks.isEmpty
                    ? const SizedBox.shrink()
                    : Container(
                        decoration: const BoxDecoration(color: Colors.blue),
                        margin: const EdgeInsets.all(10.0),
                        padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 10.0),
                        child: Row(
                          children: <Widget>[
                            Text(taskList.tasks[index].id.toString()),
                            const SizedBox(width: 20.0),
                            Text(taskList.tasks[index].name),
                            const SizedBox(width: 20.0),
                            Text(
                              'total: ${taskList.tasks[index].stats.total}/completion: ${taskList.tasks[index].stats.completion}',
                            ),
                          ],
                        ),
                      ),
                itemCount: taskList.count,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 50.0),
            child: TextButton(
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(builder: (_) => SecondPage(idIndex)));
              },
              child: const Text('二级页面'),
            ),
          ),
        ],
      )),
      floatingActionButton: ElevatedButton(
        onPressed: () {
          globalTaskList.add(Task(++idIndex, '公司$idIndex', TaskStats(30, 0)));
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
